package com.kevin.blog.web.admin;

import com.kevin.blog.po.Blog;
import com.kevin.blog.po.Tag;
import com.kevin.blog.po.User;
import com.kevin.blog.service.BlogService;
import com.kevin.blog.service.TagService;
import com.kevin.blog.service.TypeService;
import com.kevin.blog.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @Author Kevin
 * @Date 2021-04-23 20:42:42
 */
@Controller
@RequestMapping("/admin")
public class BlogController {

    private static final String INPUT = "admin/blogs-input";
    private static final String LIST = "admin/blogs";
    private static final String REDIRECT_LIST = "redirect:/admin/blogs";

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @GetMapping("/blogs")
    public String blogs(@PageableDefault(size = 6, sort = {"updateTime"},
            direction = Sort.Direction.DESC) Pageable pageable, BlogQuery blog, Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("page", blogService.listBlog(pageable, blog));
        return LIST;
    }

    /**
     * 只刷新一个片段的写法，刷新blog中的blogList片段
     *
     * @param pageable
     * @param blog
     * @param model
     * @return
     */
    @PostMapping("/blogs/search")
    public String search(@PageableDefault(size = 6, sort = {"updateTime"},
            direction = Sort.Direction.DESC) Pageable pageable, BlogQuery blog, Model model) {
        model.addAttribute("page", blogService.listBlog(pageable, blog));
        return "admin/blogs :: blogList";
    }


    /**
     * 新增页面
     *
     * @param model
     * @return
     */
    @GetMapping("/blogs/input")
    public String input(Model model) {
        setTypeAndType(model);
        model.addAttribute("blog", new Blog());
        return INPUT;
    }

    /**
     * 普通方法，传递types类型和tags标签
     *
     * @param model
     */
    private void setTypeAndType(Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTag());
    }

    /**
     * 修改页面，并使用init方法将标签的所有值从list转换成为String类型便于传到前端展示
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {
        setTypeAndType(model);
        Blog blog = blogService.getBlog(id);
        blog.init();
        model.addAttribute("blog", blog);
        return INPUT;
    }

    /**
     * 提交保存页面
     *
     * @param blog
     * @param redirectAttributes
     * @param session
     * @return
     */
    @PostMapping("/blogs")
    public String post(Blog blog, RedirectAttributes redirectAttributes,
                       HttpSession session) {
        blog.setUser((User) session.getAttribute("user"));
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagService.listTag(blog.getTagIds()));
        //判断Tag标签是否在数据库中存在，如果不存在就新增（遍历ID查询）
//        String tagIds = blog.getTagIds();
//        String tagNames = blog.getTagNames();
//        if (!tagIds.isEmpty()) {
//            String[] tagId_splits = tagIds.split(",");
//            String[] tagName_split = tagNames.split(",");
//            for (String tagId : tagId_splits) {
//                if (tagService.getTag(Long.valueOf(tagId)) == null) {
//                    Tag tag = new Tag();
//                    tag.setId(100L);
//                    tag.setName(tagName_split[Integer.parseInt(tagId)]);
//                    System.out.println(tag.toString());
//                    tagService.saveTag(tag);
//                }
//            }
//        }
        Blog b;
        if (blog.getId() == null) {
            b = blogService.saveBlog(blog);
        } else {
            b = blogService.updateBlog(blog.getId(), blog);
        }
        if (b == null) {
            redirectAttributes.addFlashAttribute("message", "操作失败");
        } else {
            redirectAttributes.addFlashAttribute("message", "操作成功");
        }
        return REDIRECT_LIST;
    }

    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        blogService.deleteBlog(id);
        redirectAttributes.addFlashAttribute("message", "删除成功");
        return REDIRECT_LIST;
    }


}
